import React from 'react'
import {withRouter} from 'react-router-dom'
import GoBackLayout from "../../layouts/GoBackLayout/GoBackLayout";
import FormInput from "../../shared-components/FormInput/FormInput";
import {Modal, NavBar, Toast} from "antd-mobile";
import constants, {GiftMapper} from "../../utils/constants";
import {formatDate, formatDateWithDot, formatScheduleDate, handleDateChange} from "../../utils/dateService";
import DateTabs from "../../shared-components/DateTabs/DateTabs";
import {addProPlanReq, fetchGameListReq} from "../../apis/goApis";
import GameListHandler from "../../model/GameList";
import selectSrc from "../../res/images/web/pro_apply/选择-未选@2x.png"
import selectedSrc from "../../res/images/web/pro_apply/选择-选中@2x.png"
import CustomButton from "../../shared-components/CustomButton/CustomBotton";
import SelectDot from "../pro-apply/SelectDot/SelectDot";
import LocalStorageService from "../../utils/LocalStorageService";
import {getPercentsArrayFromOddsArray} from "../plan-detail/plan-detail";


class AddPlan extends React.Component {

    constructor(props) {
        super(props)
        this.today = formatDate((new Date()))
        this.uid = LocalStorageService.get('userid')
        this.state = {
            sports: ['足球', '篮球', '电竞',],
            sportsActiveIndex: 0,
            types: ['亚指', '欧指', '总进球',],
            typesActiveIndex: 0,
            gameList: '',
            dateTabs: [
                {value: this.today, title: '今天', active: true,},
                {value: formatDate(handleDateChange(this.today, 1)), title: formatDateWithDot(handleDateChange(this.today, 1)), active: false},
                {value: formatDate(handleDateChange(this.today, 2)), title: formatDateWithDot(handleDateChange(this.today, 2)), active: false},
                {value: formatDate(handleDateChange(this.today, 3)), title: formatDateWithDot(handleDateChange(this.today, 3)), active: false},
            ],
            activeDateIndex: 0,
            dateGames: {},
            modal: {
                gameList: false,
            },
            gameListHandler: null,
            selectedGame: null,
            homeName: '',
            awayName: '',
            eventName: '',
            title: '',
            reason: '',
            free: true,
            yuceDatas: ['', '', '',],
            yuceRates: [0, 0, 0,],
            price: 10,
        }
    }

    onTabClick(index, tabName) {
        let indexName = tabName + 'ActiveIndex'
        this.setState({
            [indexName]: index,
        })
    }

    renderTabs(tabs, activeIndex, tabName) {
        return <div className='flex-space-between-align-center'>
            {tabs.map((tab, index,) => {
                let active = index === activeIndex
                let last = index === tabs.length - 1
                return <div
                    key={index}
                    style={{
                        flex: 1,
                        height: '32px',
                        borderRadius: '16px',
                        background: active ? '#fff' : '#F8F8F8',
                        marginRight: last ? '' : '8px',
                        textAlign: 'center',
                        boxSizing: 'border-box',
                        border: active ? '2px solid #FFA500' : '',
                    }}
                    className="flex-center-align-center"
                    onClick={() => this.onTabClick(index, tabName)}
                >
                    <span
                        style={{
                            color: active ? '#FFA500' : '#333',
                        }}
                    >{tab}</span>
                </div>
            })}
        </div>
    }

    callGameListModal() {
        this.fetchList()
        this.setState({
            modal: {
                ...this.state.modal,
                gameList: true,
            }
        })
    }

    onGameListModalClose() {
        this.setState({
            modal: {
                ...this.state.modal,
                gameList: false,
            }
        })
    }

    onDateTabClick(index) {
        const tabs = this.state.dateTabs
        let tab
        for (let i = 0; i < tabs.length; i++) {
            if (i === index) {
                tabs[i].active = true
                tab = tabs[i]
            } else {
                tabs[i].active = false
            }
        }
        this.setState({
            dateTabs: tabs,
            activeDateIndex: index,
        }, () => {
            this.fetchList()
        })
    }

    getDate = () => {
        const date = this.state.dateTabs[this.state.activeDateIndex].value
        return date
        // const currentTab = this.state.tabs.find(tab => tab.active === true)
        // return currentTab.value
    }

    fetchList = () => {
        const date = this.getDate()
        if (this.state.dateGames[date]) {
            return
        } else {
            fetchGameListReq({
                date,
            }, true)
                .then((resp) => {
                    if (resp.data.ok) {
                        const data = JSON.parse(resp.data.ok)
                        const {
                            teams,
                            events,
                            stages,
                            matches,
                        } = data
                        const handler = new GameListHandler({matches, teams, events, stages,})
                        this.setState({
                            ...this.state,
                            dateGames: {
                                ...this.state.dateGames,
                                [date]: handler,
                            },
                        })
                    }
                })
        }
    }

    renderGameCard(game) {
        const h = game.homeTeam.detail
        const a = game.awayTeam.detail
        const selected = this.state.selectedGame && game.matchId === this.state.selectedGame.matchId
        return <div
            style={{
                background: '#fff',
                margin: '2px 0',
                padding: '8px 12px 16px',
            }}
        >
            <div className='flex-space-between-align-center mg-b-12px'>
                <div style={{width: '33%', textAlign: 'left', fontSize: '12px',}}>
                    <span className='mg-r-8px'>{game.event.short_name_zh}</span>
                    <span>{formatScheduleDate(new Date(game.schedule * 1000))}</span>
                </div>
                <div style={{width: '33%', fontSize: '12px',}}>
                    <span>未</span>
                </div>
                <div style={{width: '33%', textAlign: 'right',}}>
                    <img src={selected ? selectedSrc : selectSrc} style={{width: 16, height: 16,}} alt=''/>
                </div>
            </div>
            <div className="flex-space-between-align-center">
                <span style={{
                    width: '40%',
                    textAlign: 'right',
                    fontSize: '14px',
                    color: '#333333',
                    lineHeight: '18px',
                }}>{h.name_zh}</span>
                <span style={{width: '20%',}}>-</span>
                <span
                    style={{
                        width: '40%',
                        textAlign: 'left',
                        fontSize: '14px',
                        color: '#333333',
                        lineHeight: '18px',
                    }}
                >{a.name_zh}</span>
            </div>
        </div>
    }

    selectGame(game) {
        this.setState({
            selectedGame: game,
        })
    }

    saveSelectedGameInfo() {
        let g = this.state.selectedGame
        if (g) {
            this.setState({
                homeName: g.homeTeam.detail.name_zh,
                awayName: g.awayTeam.detail.name_zh,
                eventName: g.event.name_zh,
            })
        }
        this.onGameListModalClose()
    }

    renderGameList(gameHandler) {
        if (gameHandler) {
            return gameHandler
                .listSchedule()
                .map((game,i) => {
                    return <div
                        key={i}
                        onClick={() => this.selectGame(game)}
                    >
                        {this.renderGameCard(game)}
                    </div>
                })
        }
        return null
    }

    toggleProFree() {

        this.setState({
            free: !this.state.free,
        })
    }

    addProPlan() {
        //     type AddSchemeJson struct {
        //     Namiid      int       //比赛的纳米id
        //     Uid         string    //用户uid
        //     Reasontitle string    //方案理由标题
        //     Reason      string    //方案理由
        //     Yucestyle   string    //预测类型(让球=asia，大小球=bs，胜平负=eu)
        //     Yuce        []float64 //方案数据
        //     Price       int       //方案价格(爱心),0为免费
        const yuceStyles = ['asia', 'eu', 'bs']
        addProPlanReq({
            Namiid: this.state.selectedGame.matchId,
            Uid: this.uid,
            Reasontitle: this.state.title,
            Reason: this.state.reason,
            Yucestyle: yuceStyles[this.state.typesActiveIndex],
            Yuce: this.state.yuceDatas.map(d => parseFloat(d)),
            Price: this.state.free ? 0 : 10,
        })
            .then((resp) => {
                if (resp.data.ok === 1) {
                    Toast.success('方案发布成功！', 1)
                    setTimeout(() => {
                        this.props.history.goBack()
                    }, 1000)
                }
            })
    }

    renderOddsSummary() {
        const titlesArray = [
            ['主胜概率', '', '客胜概率',],
            ['主胜概率', '平局概率', '客胜概率',],
            ['大球概率', '', '小球概率',],
        ]
        const colors = ['#FA7268', '#FFA500', '#36C8B9']
        const titleArray = titlesArray[this.state.typesActiveIndex]
        const isSPF = this.state.typesActiveIndex === 1
        const titles =  titleArray.map((title, index) => {
            if (title) {
                return <div
                    style={{
                        // textAlign: 'center',
                        height: isSPF ? 138 * 0.33 : 138 * 0.5,
                    }}
                    key={index}
                >
                    <p>{title}</p>
                    <p
                        style={{
                            color: colors[index],
                            marginTop: isSPF ? '4px' : '8px',
                            fontSize: isSPF ? '22px' : '28px',
                            fontWeight: '500',
                            lineHeight: isSPF ? '22px' : '28px',

                        }}
                    >{this.state.yuceRates[index] + '%'}</p>
                </div>
            }
        })
        return <div
            style={{
                display: 'flex',
                flexDirection: 'column',
                justifyContent: 'space-between',
                alignItems: 'center',
                position: 'relative',
            }}
        >
            {titles}

        </div>
    }

    onRateDatasConfirm() {
        const datas = this.state.yuceDatas.map(float => parseFloat(float))
        const ps = getPercentsArrayFromOddsArray(datas, ['asia', 'eu', 'bs'][this.state.typesActiveIndex])
        this.setState({
            yuceRates: ps,
        })
    }

    render() {
        return <>
            <Modal
                visible={this.state.modal.gameList}
                onClose={() => this.onGameListModalClose()}
            >
                <NavBar
                    style={{backgroundColor: `${constants.themeColor}`}}
                >
                    赛程
                </NavBar>
                <div style={{background: '#F8F8F8', position: 'relative',}}>
                    <DateTabs
                        tabs={this.state.dateTabs}
                        onTabSelected={(index) => this.onDateTabClick(index)}
                        today={this.today}
                    />
                    <div
                        style={{
                            height: window.innerHeight - 45 - 48,
                            overflowY: 'scroll',
                        }}
                    >
                        {this.renderGameList(this.state.dateGames[this.getDate()])}
                        <div
                            style={{
                                width: 'calc(100% - 32px)',
                                padding: '24px 16px',
                                position: 'absolute',
                                bottom: 0,
                                left: 0,
                            }}
                        >
                            <div className='flex'>
                                <CustomButton
                                    bg='#fff'
                                    color='#333'
                                    extrastyle={{
                                        marginRight: '8px',
                                    }}
                                    onClick={() => this.onGameListModalClose()}
                                >
                                    取消
                                </CustomButton>
                                <CustomButton
                                    onClick={() => this.saveSelectedGameInfo()}
                                >
                                    保存
                                </CustomButton>
                            </div>

                        </div>
                    </div>
                </div>
            </Modal>
            <GoBackLayout
                mainTitle='发布方案'
                history={this.props.history}
            >
                <div
                    style={{
                        background: '#fff',
                        padding: '16px',
                        marginTop: '2px',
                        marginBottom: '8px',
                    }}
                >
                    <p className='mg-b-16px'>
                        体育分类
                    </p>
                    {this.renderTabs(this.state.sports, this.state.sportsActiveIndex, 'sports',)}
                </div>
                <div
                    style={{
                        background: '#fff',
                        padding: '16px',
                        marginTop: '2px',
                        marginBottom: '8px',
                    }}
                    onClick={() => this.callGameListModal()}
                >
                    <p className='mg-b-16px'>
                        赛事名称
                    </p>

                    <div className="mg-b-12px">
                        <FormInput
                            placeholder='请输入赛事名称（例:英超）'
                            value={this.state.eventName}
                            readOnly
                        />
                    </div>

                    <div className='flex-space-between-align-center'>
                        <div>
                            <p>主队</p>
                            <FormInput
                                placeholder='请输入主队名称'
                                readOnly
                                value={this.state.homeName}
                            />
                        </div>

                        <div>
                            <p>客队</p>
                            <FormInput
                                placeholder='请输入客队名称'
                                readOnly
                                value={this.state.awayName}
                            />
                        </div>
                    </div>
                </div>
                <div
                    style={{
                        background: '#fff',
                        padding: '16px',
                        marginBottom: '8px',
                    }}
                >
                    <p className='mg-b-16px'>
                        赛事分类
                    </p>
                    {this.renderTabs(this.state.types, this.state.typesActiveIndex, 'types',)}
                    <div
                        className='pd-12'
                        style={{
                            background: '#FAFAFA',
                            marginTop: '14px',
                            position: 'relative',
                        }}
                    >
                        <div className='flex mg-b-16px'>
                            <p style={{flex: 2, fontSize: 14, lineHeight: '20px',}}>您的主张</p>
                            <div style={{flex: 2,}}>
                                {this.state.yuceDatas.map((data, index) => {
                                    const placeholders = [
                                        ['主胜概率', '让球', '客胜概率',],
                                        ['主胜概率', '平局概率', '客胜概率',],
                                        ['大球概率', '指数', '小球概率',],
                                    ]
                                    return <FormInput
                                        value={data}
                                        onChange={e => {
                                            const ds = this.state.yuceDatas
                                            ds[index] = e.target.value
                                            this.setState({
                                                yuceDatas: ds,
                                            })
                                        }}
                                        placeholder={placeholders[this.state.typesActiveIndex][index]}
                                        key={index}
                                        extraStyle={{
                                            background: '#FAFAFA',
                                            padding: 0,
                                            height: 30,
                                            marginTop: index === 0 ? '' : '24px',
                                        }}
                                        extraInputStyle={{
                                            background: '#FAFAFA',
                                            height: 'auto',
                                            lineHeight: 1,
                                            fontSize: 14,
                                        }}
                                    />
                                })}
                            </div>

                            <div style={{flex: 2,}}>
                                {this.renderOddsSummary()}
                            </div>

                        </div>

                        <CustomButton
                            extrastyle={
                                this.state.yuceDatas.every(data => data.length > 0) ? {} : {
                                    background: '#F1F1F1',
                                    color: 'rgba(51, 51, 51, 0.4)',
                                }
                            }
                            onClick={() => this.onRateDatasConfirm()}
                        >
                            确让主张
                        </CustomButton>

                        <div
                            style={{
                                width: '0px;height:0px;margin:100px auto',
                                borderLeft: '12px solid transparent',
                                borderRight: '12px solid transparent',
                                borderBottom: '12px solid #FAFAFA',
                                position: 'absolute',
                                top: '-12px',
                                left: 33 * (this.state.typesActiveIndex + 1) - 16.5 + '%',
                                transform: 'translateX(-50%)',
                            }}
                        />
                    </div>


                </div>

                <div
                    style={{
                        background: '#fff',
                        padding: '16px',
                        marginBottom: '8px',
                    }}
                >
                    <p>
                        方案标题
                    </p>
                    <FormInput
                        value={this.state.title}
                        onChange={e => this.setState({title: e.target.value,})}
                        placeholder='请输入方案标题'
                    />
                    <p className='mg-b-16px mg-t-16px'>
                        赛事名称
                    </p>
                    <textarea
                        style={{
                            boxSizing: 'border-box',
                            width: '100%',
                            height: '100px',
                            background: '#F3F3F3',
                            padding: '12px 16px',
                        }}
                        placeholder='请输入您的方案内容...'
                        value={this.state.reason}
                        onChange={e => this.setState({reason: e.target.value,})}
                    />
                </div>
                <div
                    style={{
                        background: '#fff',
                        padding: '16px 16px 12px',
                        marginBottom: '8px',
                    }}
                >
                    <p className='mg-b-16px'>
                        收费类型
                    </p>
                    <div className='flex-space-between-align-center'
                         style={{marginBottom: '20px',}}
                         onClick={() => this.toggleProFree()}
                    >
                        <span>免费</span>
                        <SelectDot select={this.state.free}/>
                    </div>
                    <div className='flex-space-between-align-center'
                         onClick={() => this.toggleProFree()}
                    >
                        <div className='flex-align-center'>
                            <span>收费</span>
                            <img alt='' src={GiftMapper['gift_9'].src} style={{width: 20, height: 20, margin: '0 8px 0 20px',}}/>
                            <span>{this.state.price}</span>
                        </div>

                        <SelectDot select={!this.state.free}/>
                    </div>
                </div>

                <div
                    style={{padding: '16px 12px',}}
                >
                    <CustomButton
                        onClick={() => this.addProPlan()}
                    >
                        发布
                    </CustomButton>

                </div>

            </GoBackLayout>
        </>
    }
}



export default withRouter(AddPlan)